from fastapi import Request

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.token import Token
from util.str import Str

async def GetSheetList(req: Request):
    try:
        token = req.headers.get("token")
        if Token().verify_token(token) == None:
            return Result.error(BaseEnum.TOKEN_INVALID_ERROR)
        
        user = await UserService.getUserByToken(token)
        if user == None:
            return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
        
        sheetList = await SongService.getSheetListByUserId(user.id)

        sheetIdList = [item.id for item in sheetList]
        sheetFavorites = await SongService.getFavoriteListBySheetIdList(sheetIdList)
        
        res = []
        for item in sheetList:
            tmp = dict(item)
            size = 0
            for favorite in sheetFavorites:
                if item.id == favorite.sheet_id:
                    size += 1
            tmp.update(sheetSize=size)
            res.append(tmp)

        return Result.success(res)
    except Exception as e:
        Log.error('获取 song sheet 列表异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)